<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\ArticlesController;
use App\Models\Article;
use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\Tag;
use App\Models\User;
use Encore\Admin\Admin;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use function GuzzleHttp\Psr7\str;
use Illuminate\Support\Facades\DB;
use Encore\Admin\Widgets\Table;

class ArticleController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('文章')
            ->description('文章管理')
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('文章详情')
            ->description('')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('编辑')
            ->description('文章编辑')
            ->body($this->form()->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('新建')
            ->description('新建文章')
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Article);
        $article = new Article();
        $grid->title('标题')->display(function($text) use($article){
            return '<a target="_blank" href='.route('articles.show', array_merge([$this->id, $this->slug])).'>'.str_limit($text, 20, '...')."</a>";
        });;
        $grid->excerpt('摘要')->display(function($text) {
            return str_limit($text, 35, '...');
        });
        $grid->user_id('用户')->display(function ($user_id) {
            $adminArt = new ArticleController();
            return $adminArt->dealUserGrid($user_id);
        });
        $grid->category_id('分类')->display(function ($category_id) {
            $category = Category::where('id',$category_id)->select('name')->first();
            return  $category->name;
        });
        $grid->tags('标签')->display(function () {
            $tag = new Tag();
            $tags = $tag->getTag($this->tags)->toArray();
            return array_column($tags,'name');
        })->label();
        $grid->reply_count('回复数')->sortable();
        $grid->view_count('查看总数')->sortable();
        $grid->last_reply_user_id('Last Reply')->display(function ($user_id) {
            if ($user_id){
                $article  = new ArticleController();
                return $article->dealUserGrid($user_id);
            }else{
                return '无';
            }
        });
        $grid->order('排序')->sortable();
        $grid->created_at('创建时间')->sortable();
        $grid->updated_at('更新时间')->sortable();

        return $grid;
    }

    public function dealUserGrid($user_id)
    {
        $user = User::where('id',$user_id)->select('avatar','id')->first();
        $avatar = $user->avatar;
        if (substr($avatar , 0 , 4)=='http')
            return "<a target='_blank' href=".route('users.show',$user->id)."><img src='$avatar' width='30' height='30'/></a>";
        else
            return "<a target='_blank' href=".route('users.show',$user->id)."><img src='upload/$avatar' width='30' height='30'/></a>";
    }
    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $article = Article::findOrFail($id);
        $tag = new Tag();
        //文章信息
        $article->category = DB::table('categories')->where('id',$article->category_id)->select()->first();
        //用户信息
        $user =$article->user()->first();
        //文章标签
        $article->tags = $tag->getTag($article->tags);
        //相关文章
        $articles  = DB::table('articles')
            ->where('category_id',$article->category_id)
            ->inRandomOrder()
            ->take(10)
            ->select(['id','title'])
            ->get();
        return  view('admin.articles.show', compact('article','user','tags','articles'));

    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Article);
        $tag = new Tag();
        $category = new Category();
        $user = new User();

        $form->text('title', 'Title');
        $form->simditor('body', '文章主体');
        $form->select('user_id', '发布用户')
            ->options($user::all()->pluck('name','id'))
            ->rules('required');
        $form->select('category_id', '分类（必选）')
            ->options($category::all()->pluck('name','id'))
            ->rules('required');
        $form->multipleSelect('tags','标签（必选）')
            ->options($tag::all()->pluck('name','id'))
            ->rules('required');
        $form->number('reply_count', '回复总数（可选）')->default(0);
        $form->number('view_count', '查看总数（可选）')->default(0);
        $form->number('order', '文章排序（可选）')->default(0);
        $form->datetime('created_at','创建时间');
        $form->saving(function (Form $form) {
            $form->tags = trim(implode(',',array_filter($form->tags)));
        });
        return $form;
    }
}
